package cn.mln521.web.servlet;

import cn.mln521.dao.UserDao;
import cn.mln521.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置request编码
        request.setCharacterEncoding("utf-8");
        // 2.获取验证码
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //删除session中存储的验证码 防止验证码二次使用
        session.removeAttribute("checkCode_session");
        // 3.获取参数
        Map<String, String[]> map = request.getParameterMap();
        User loginUser = new User();
        try {
            // 封装参数
            BeanUtils.populate(loginUser, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 4.先判断验证码是否正确
        if (checkCode_session != null && checkCode_session.equalsIgnoreCase(loginUser.getCheckCode())) {
            // 调用dao方法
            UserDao dao = new UserDao();
            User user = dao.login(loginUser);
            if (user != null) {
                // 用户名存在
                // 把user存储到session
                session.setAttribute("user", user.getUsername());
                // 重定向到success.jsp页面
                response.sendRedirect(request.getContextPath() + "/success.jsp");
            } else {
                // 用户名或者密码不正确
                // 存储提示信息到request
                request.setAttribute("login_error", "用户名或者密码不正确");
                // 转发到登陆页面
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } else {
            // 验证码不一致
            // 存储提示信息到request
            request.setAttribute("cc_error", "验证码错误");
            // 转发到登陆页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
